package com.itheima.web.controller.store;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Course;
import com.itheima.utils.BeanUtil;
import com.itheima.web.BaseServlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/store/course")
public class CourseServlet extends BaseServlet {
    /**
     * 分页查询的方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");
        String size = req.getParameter("size");

        PageInfo<Course> list = courseService.findAll(page, size);
        req.setAttribute("page", list);
        req.getRequestDispatcher("/WEB-INF/pages/store/course/list.jsp").forward(req, resp);
    }

    /**
     * 添加的界面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/pages/store/course/add.jsp").forward(req, resp);
    }

    /**
     * 添加方法
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Course course = BeanUtil.fillBean(req, Course.class, "yyyy-MM-dd");
        courseService.save(course);
        //重定向到list界面
        resp.sendRedirect(req.getContextPath() + "/store/course?operation=list");
    }

    /**
     * 跳转到编辑页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询需要修改的id,然后数据回显到修改页面
        String id = req.getParameter("id");
        Course course = courseService.findById(id);
        //放置在请求域中
        req.setAttribute("course",course);
        req.getRequestDispatcher("/WEB-INF/pages/store/course/update.jsp").forward(req,resp);
    }

    /**
     * 修改
     * @param req
     * @param resp
     * @throws IOException
     */
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Course course = BeanUtil.fillBean(req, Course.class, "yyyy-MM-dd");
        courseService.update(course);
        resp.sendRedirect(req.getContextPath()+"/store/course?operation=list");
    }

    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        courseService.delete(id);
        resp.sendRedirect(req.getContextPath()+"/store/course?operation=list");
    }
}
